<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\Sku as SkuService;
use app\common\service\Material as MaterialService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\MaterialReturn as MaterialReturnService;
use think\Db;
/**
 * 退料进度
 * @author King
 *
 */
class MaterialReturn extends Admin
{

	protected $hisiModel = 'MaterialReturn';//模型名称[通用添加、修改专用]
	protected $hisiValidate = 'MaterialReturn';
	protected $hisiAddScene = '';//添加数据验证场景名
	protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }
	/**
     * 退换料进度
     * @author sparkguo
     * return json
     */
    public function index()
    {
    	$status       = $this->request->param('status/s', 0);
    	$systemUserKV = getSystemUserKV(null);
		$factoryKV = getFactoryKV(false);
        $stallsKV= getStallsKV();
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$clientOrdernum    = $this->request->param('client_ordernum/s', '');
    		$sku    = $this->request->param('sku/s', '');
    		$createDateRange    = $this->request->param('create_date_range/s');
			$export     = $this->request->param('export/d', 0);
            $factory_id    = $this->request->param('factory_id');
            $stall_id=$this->request->param('stall_id/d','');
            $creater=$this->request->param('creater','');
            $giveback_time    = $this->request->param('giveback_time/s','');
            $reason    = $this->request->param('reason/s','');
			$wheres=[];
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			if ($status !== '') {
    			$where[] = ['mr.status', '=', $status];
    		}
            if (substr($clientOrdernum, 0, 1) == 'B') {
                $where[] = ['mr.order_material_id', '=', substr($clientOrdernum, 1, 10)];
            } else {
                if ($clientOrdernum != '') {
                    $where[] = ['mr.client_ordernum', '=', $clientOrdernum];
                }
            }
            if ($reason != '') {
                $where[] = ['mr.reason','like', "%{$reason}%"];
            }
            if ($giveback_time != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $giveback_time));
                $where[] = ['mr.giveback_time', 'between', [$startTime, $endTime+86399]];
            }
    		$orderJoinType='left';
            if ($factory_id != '') {
                $orderJoinType='inner';
                $where[] = ['o.factory_id', '=', $factory_id];
            }
            $materialItemType='left';
            if ($stall_id != '') {
                $materialItemType='inner';
                $where[] = ['item.stalls_id', '=', $stall_id];
            }
            if ($creater != '') {
                $where[] = ['admin_id', 'in', db('system_user')->where('nick', 'like', "%{$creater}%")->column('id')];
            }

    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['mr.create_time', 'between', [$startTime, $endTime+86399]];
    		}

    		$orderService = new OrderService();
    		$materialService = new MaterialService();
    		$orderMaterialService = new OrderMaterialService();
    		$orderMaterialItemService = new OrderMaterialItemService();
			$skuService = new SkuService();

    		$order = 'update_time desc';
    		$list = db('material_return mr')
    		->join('order o', "mr.order_id=o.id", $orderJoinType)
    		->join('order_material om', "mr.order_material_id=om.mid", 'right')
            ->join("order_material_item item","mr.order_material_item_id=item.id",$materialItemType)
    		->field("concat(mr.order_material_id,'+', mr.`status`) as omi_s,mr.*,o.create_time as order_create_time,count(mr.order_material_id) as rt_tiaoshu,o.factory_id,o.group_id,o.sku,o.create_time as order_time,item.stalls_id,
    		o.over_time,o.shipment_time,o.is_auto_import,o.status as order_status,o.quantity,o.o_type,o.type,mr.type as return_type")->where($where)->page($page)->limit($limit)->order($order)->group('omi_s')->select();
    		$abolishNum=[];
    		$data['data'] = [];
    		foreach ($list as $k => $v) {
    			$v['omInfo'] = $omInfo = $orderMaterialService->getInfoById($v['order_material_id']);
				if(empty($omInfo)) {
					if (isset($abolishNum[$v['status']])) $abolishNum[$v['status']]++;
					else $abolishNum[$v['status']] = 1;
					continue;
				}
				$v['giveback_time']=$v['giveback_time']>0 ? date("Y-m-d",$v['giveback_time']) : '';
				$v['mInfo'] = $mInfo = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum');
				$v['sInfo'] = $skuService->getInfoBySku($v['sku']);
                $v['rt_type']=$v['return_type']==1? '整匹':'按米退';
				$materialDosage = $omInfo['material_dosage'];
				$v['total_material_dosage'] = round($v['quantity'] * $materialDosage, 2);
				$v['rtInfo'][0]=[
					'id'=>$v['id'],
					'order_material_id'=>$v['order_material_id'],
					'material_sku'=>$mInfo['material_sku'],
					'create_time'=>$v['create_time'],
					'name'=>$mInfo['name'],
					'rttype'=>$mInfo['type'],
					'rt_tiaoshu'=>$v['rt_tiaoshu'],
					'model'=>$mInfo['model'],
					'colornum'=>$mInfo['colornum'],
					'color'=>$mInfo['color'],
					'total_material_dosage'=>round($v['quantity'] * $materialDosage, 2),
					'status'=>$v['status'],
					'material_sku'=>$mInfo['material_sku'],
				];
                $v['supplier']="";
                if($v['stalls_id']) $v['supplier']= arrayGet($stallsKV, $v['stalls_id']);
				$v['admin_id_name']=arrayGet($systemUserKV, $v['admin_id'], '');
				$v['is_auto_import_name'] = arrayGet(config('mimo.order_from'), $v['is_auto_import'], '');
				$v['duty_admin_name'] = arrayGet($systemUserKV, $v['duty_admin_id'], '');
				$v['audit_admin_name'] = arrayGet($systemUserKV, $v['audit_admin_id'], '');

				$v['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$v['shipment_time_diff'] = $v['order_status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
				$v['create_time_diff'] = $v['order_status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                $v=array_merge($v['rtInfo'][0],$v);
				$data['data'][] = $v;
    		}
			//导出
            if ($export) {
                $this->_exportXls('退换料进度-' .date('YmdHis'), $data['data']);
                exit;
            }
    		$data['count'] = db('material_return mr')
                ->join('order o', "mr.order_id=o.id", $orderJoinType)
                ->join('order_material om', "mr.order_material_id=om.mid", 'right')
                ->join("order_material_item item","mr.order_material_item_id=item.id",$materialItemType)
                ->field("concat(mr.order_material_id,'+', mr.`status`) as omi_s")->where($where)->group('omi_s')->count('mr.id');
    		$data['code'] = 0;
    		$data['msg'] = '';
			$data['status'] = $status;
			$data['abolishNum']=$abolishNum;
			foreach ($where as $kw => $vw) {
				if($vw[0]=='mr.status')	 continue;
				$wheres[]=$vw;
			}

			$statSql =db('material_return mr')
                ->join('order o', "mr.order_id=o.id", $orderJoinType)
                ->join('order_material om', "mr.order_material_id=om.mid", 'right')
                ->join("order_material_item item","mr.order_material_item_id=item.id",$materialItemType)
                ->field("concat(mr.order_material_id,'+', mr.`status`) as omi_s,mr.*,count(mr.order_material_id) as rt_tiaoshu,o.factory_id,o.group_id,o.sku,o.create_time as order_time,item.stalls_id,
    		o.over_time as tover_time,o.shipment_time,o.is_auto_import,o.status as order_status,o.quantity,o.o_type,mr.type as return_type")->where($wheres)->group('omi_s')->buildSql();
			$statData1 = Db::query("select `status`,count(status) as num from($statSql) a where status is not null GROUP BY `status`");//dump($statSql);
			$data['statData']=[];
			foreach ($statData1 as $key => $value) {
				$data['statData'][$value['status']]=$value['num'];
			}
    		return json($data);
    	}
        $statData=[0,0,0,0];
    	$assign = [
    		'status' => $status,'factoryKV'=>['' => '请选择']+$factoryKV,'stallsKV'=>['' => '请选择']+$stallsKV,
			'statData'=>$statData
    	];
    	return $this->assign($assign)->fetch();
    }

	/**
	 * 退换料进度导出
	 *
	 * @author King
	 * @date 2020年9月22日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				$v['id'],
				date('Y-m-d H:i:s', $v['create_time']),
				$v['client_ordernum'],
				$v['omInfo']['tiaoshu'],
				$v['cloth_num'],
				$v['mInfo']['name'],
				$v['mInfo']['color'],
				$v['omInfo']['caigou_status'] == 1 ? '是':'否',
				$v['omInfo']['create_time']==''? '': date('Y-m-d H:i:s',$v['omInfo']['create_time']),
				$v['cost_time_text'],
				$v['reason'],
				$v['admin_name'],
				$v['duty_admin_name'],
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['编号','创建日期','订单号','总匹数','布号','物料名称','颜色','批色','到料日期','退料历时','退料原因','发起人','负责人'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}

    /**
     * 退换料
     *
     */
    public function status()
    {
    	$val        = $this->request->param('val/d', 0);
    	$ids         = $this->request->param('id', []);
    	$action=$this->request->param('action', '');
    	if($action=='setFieldVal'){
            return $this->_setReturnMaterialData();
        }
    	if (empty($ids)) {
    		return $this->error('缺少id参数');
    	}
    	if (!in_array($val, [1, 2])) {
    		return $this->error('参数错误');
    	}
    	try {
    		db()->startTrans();
			$orderMaterialService= new OrderMaterialService();
			foreach ($ids as $key => $id) {
				$materialReturnService = new MaterialReturnService();
				$mrInfo = $materialReturnService->getInfoById($id);
				if (empty($mrInfo)) {
					return $this->error('未找到相关记录');
				}
				$orderId = $mrInfo['order_id'];
				$materialId = $mrInfo['material_id'];
				$upData = [
					'status' => $val,
					'is_delivery' => 1,
					'update_time' => time(),
					'duty_admin_id' => ADMIN_ID,
				];
				if ($val == 1) $upData['is_renew'] = 1;

				db('material_return')->where('id', $id)->update($upData);
                if ($val == 1) {//换料中--作用到物料进度
                    $orderMaterialService->material_return_update_tuiliao($id);
                }

				// 记录退换料操作日志
				$materialReturnService->addLog($id, $val == 1?4:3);

				$orderMaterialService = new OrderMaterialService();
				$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);

				// 如果未有减扣过条数，且是整条退料，则需减扣条数
				if($mrInfo['is_reduce'] == 0 && $mrInfo['type'] == 1) {
					// 扣除条数
					if ($omInfo && $omInfo['tiaoshu'] > 0) {
//						$omData = [
//							'tiaoshu' => $omInfo['tiaoshu']-1,
//							'shiji_caigou_count' => $omInfo['tiaoshu']-1,
//							'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
//						];
//						db('order_material')->where('mid', $omInfo['mid'])->update($omData);
					}

					db('material_return')->where('id', $id)->update(['is_reduce' => 1]);
				}
                db('order_material')->where('mid', $mrInfo['order_material_id'])->update(['return_notconfirm'=>0]);//退料审核更新为已审核
				$orderMaterialService->updateCaichuangStatusV2($orderId,$mrInfo['order_material_id']);//更新裁剪状态

				$this->addOrderLog($orderId, $mrInfo['client_ordernum'], "物料[".arrayGet(arrayGet($omInfo, 'mInfo', []), 'name', '')."]退换料进度[".($val == 1?'确认换料':'确认退料')."]");

			}
    		db()->commit();
    		return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    //设置回料时间，处理备注等
    private function _setReturnMaterialData(){
        $id=$this->request->param('id', '');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        $fieldName=$this->request->param('field', '');
        $fieldval=$this->request->param('fieldval', '');
        $fieldval=$fieldName=='giveback_time'? strtotime($fieldval) :$fieldval;
        if(in_array($fieldName,['giveback_time','remark'])){
            db('material_return')->where('id', $id)->update([$fieldName => $fieldval]);
        }
        if(in_array($fieldName,['stalls_id'])){
            db('order_material_item')->where('id', $id)->update([$fieldName => $fieldval]);
        }
        return $this->Json(1);
    }

	/**
     * 物料详情
     *
     * @date 2020年11月6日
     *
     */
    public function rtClothDetail()
    {
    	$orderMaterialId  = $this->request->param('order_material_id/d', '');
		$val        = $this->request->param('val/d', 0);
		$status        = $this->request->param('status/s', '');
		$a        = $this->request->param('a/s', '');
    	if ($this->request->isAjax()) {
			$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);

			$where      = $data = [];
			if (empty($orderMaterialId)) {
				return $this->error('缺少order_material_id参数');
			}
			if($status!=''){
				$where[]=['status','=',$status];
			}
			if($a=="add"){
				$where[]=['status','in','0,1'];
				$status=5;
			}else if($a=="check"){
				$status=4;
			}
			$materialService=new MaterialService();
			$stallsKV= getStallsKV();
			$orderMaterialItemService = new OrderMaterialItemService();
			$order="id desc";
			$data['data']=[];
			$where[]=['order_material_id','=',$orderMaterialId];
			$rmList= db('material_return')->where($where)->page($page)->limit($limit)->order($order)->select();
			foreach ($rmList as $k => $v) {
				$omiInfo=$orderMaterialItemService->getInfoById($v['order_material_item_id'],"stalls_id");
				$mInfo=$materialService->getInfoById($v['material_id']);
				$v['supplier']="";
				if($omiInfo) $v['supplier']= arrayGet($stallsKV, $omiInfo['stalls_id']);

				$v['material_type']=$mInfo['type'];
				$v['material_sku']=$mInfo['material_sku'];
				$v['rt_type']=$v['type']==1? '整匹':'按米退';
				$data['data'][]=$v;
			}

			$data['count'] = db('material_return')->where('order_material_id',$orderMaterialId)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
			$data['status'] = $status;

    		return json($data);
    	}

    	$assign = [
    		'order_material_id' => $orderMaterialId,
			'val'=>$val,
			'status'=>$status,
			'a'=>$a
    	];
    	return $this->assign($assign)->fetch();
    }
    /**
     * 审核
     *
     * @author King
     * @date 2020年9月28日
     *
     */
    public function audit() {
    	$ids         = $this->request->param('id', []);
    	$id  = $this->request->param('id/d', 0);
		$mid  = $this->request->param('mid/d', 0);
		$billingCaigouCountFeed  = abs($this->request->param('billing_caigou_count_feed/f',0));
    	if (empty($id)) {
    		return $this->error('缺少id参数');
    	}
		$orderMaterialService = new OrderMaterialService();
    	$materialReturnService = new MaterialReturnService();
		$orderMaterialItemService=new OrderMaterialItemService();
    	$mrInfo = $materialReturnService->getInfoById($id);

    	if (empty($mrInfo)) {
    		return $this->error('未找到相关记录');
    	}
		$omiInfo=$orderMaterialItemService->getInfoById($mrInfo['order_material_item_id']);
		$omInfo=$orderMaterialService->getInfoById($mid);
		if($omInfo['billing_caigou_count']<$billingCaigouCountFeed) return $this->error('退量不能大于开单采购量');
    	try {
    		db()->startTrans();
			$billingCaigouCountFeedAll=$omInfo['billing_caigou_count_feed'].'-'.$billingCaigouCountFeed;
			$billingCaigouCount= round($omInfo['billing_caigou_count'])-$billingCaigouCountFeed;
			$oud = array(
	    		'update_time' => time(),
	    		'billing_caigou_count_feed' => $billingCaigouCountFeedAll,
	    		'billing_caigou_count' => $billingCaigouCount,
	    		'caigou_subtotal_money' => round($billingCaigouCount * $omInfo['caigou_unitprice'], 2),
	    	);
			db('order_material')->where('mid', $mid)->update($oud);
			//新增补退明细表记录
			$sfData=[
				'billing_caigou_count_feed'=>'-'.$billingCaigouCountFeed,
				'order_material_id'=>$mid,
				'order_id'=>$omInfo['order_id'],
				'client_ordernum'=>$omInfo['client_ordernum'],
				'material_id'=>$omInfo['material_id'],
				'admin_id'=>ADMIN_ID,
				'stall_id'=>$omiInfo['stalls_id'],
				'update_time' => time(),
				'create_time' => time(),
			];
			db('stall_feed')->insert($sfData);
			foreach ($ids as $key => $id) {
				$upData = [
					'status' => 3,
					'update_time' => time(),
					'audit_admin_id' => ADMIN_ID,
				];
				db('material_return')->where('id', $id)->update($upData);

				$materialReturnService->addLog($id, 5);
				$this->addOrderLog($mrInfo['order_id'], $mrInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]退换料进度[确认审核]");
			}
			//更新裁床状态
			$orderMaterialService->updateCaichuangStatusV2($omInfo['order_id'],$mid);
	    	db()->commit();
	    	return $this->Json(1);
	    } catch (\Exception $e) {
	    	db()->rollback();
	    	return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
	    }
    }

    /**
     * 退换料操作日志
     *
     * @author King
     * @date 2020年9月28日
     *
     * @return Json
     */
    public function log()
    {
    	$materialReturnId   = $this->request->param('id/d', 0);	// material_return表ID

    	$systemUserKV = getSystemUserKV(null);
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);

    		$where = [
    			['material_return_id', '=', $materialReturnId]
    		];
    		$order = 'id desc';
    		$data['data'] = db('material_return_log')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['admin_name'] = arrayGet($systemUserKV, $v['admin_id'], '');
    		}

    		$data['count'] = db('material_return_log')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
    	$assign = [
    		'materialReturnId' => $materialReturnId
    	];
    	return $this->assign($assign)->fetch();
    }

	/**
     * 出库打印
     *
     * @author 飞燕
     * @date 2021年4月07日
     *
     * @return Json
     */
    public function deliveryPrint()
    {
		$a=$this->request->param('a/s');
    	$systemUserKV = getSystemUserKV(null);
		$stallsKV= getStallsKV();
    	if ($a&&$a=="get") {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
			$clientOrdernum      = $this->request->param('client_ordernum/s', '');
			$name      = $this->request->param('name/s', '');
			$stallId      = $this->request->param('stall_id/d', 0);
			$materialService=new materialService();
			if($clientOrdernum) $where[]=['client_ordernum','in',$clientOrdernum];
			if($name){
				$ids=db('material')->where("name like '%".$name."%'")->column('id');
				$where[]=['material_id','in',$ids];

			}
			if($stallId){
				$omiIds=db('order_material_item')->where('stalls_id',$stallId)->column('id');
				$where[]=['order_material_item_id','in',$omiIds];
			}
			$orderMaterialItemService=new OrderMaterialItemService();
    		$where[]=['is_delivery','=',1];
    		$order = 'id desc';
    		$order = 'update_time desc';
    		$data['data'] = db('material_return')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum');
				$omiInfo=$orderMaterialItemService->getInfoById($v['order_material_item_id']);
				$data['data'][$k]['stall_id']=$omiInfo?$omiInfo['stalls_id']:0;
				$data['data'][$k]['stall_name']=$omiInfo?arrayGet($stallsKV, $omiInfo['stalls_id'],''):'';
				$data['data'][$k]['type_num'] = $v['type']==1?'整条退':'按米退';
    		}

    		$data['count'] = db('material_return')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
    	$assign = [
			'stallsKV' => ['0' => '请选择'] + $stallsKV
    	];
    	return $this->assign($assign)->fetch();
    }

	/**
     * 出库打印
     *
     * @author 飞燕
     * @date 2021年4月07日
     *
     * @return Json
     */
    public function deliveryLog()
    {
		$a=$this->request->param('a/s');
    	$systemUserKV = getSystemUserKV(null);
		$stallsKV= getStallsKV();
    	if ($a && $a=="get") {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
			$clientOrdernum      = $this->request->param('client_ordernum/s', '');
			$name      = $this->request->param('name/s', '');
			$stallId      = $this->request->param('stall_id/d', 0);
			$deliveryTime    = $this->request->param('delivery_time/s');
			$materialService=new materialService();
			if($clientOrdernum) $where[]=['client_ordernum','in',$clientOrdernum];
			if($name){
				$ids=db('material')->where("name like '%".$name."%'")->column('id');
				$where[]=['material_id','in',$ids];
			}
			if ($deliveryTime != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $deliveryTime));
                $where[] = ['delivery_time', 'between', [$startTime, $endTime+86399]];
            }
			if($stallId){
				$omiIds=db('order_material_item')->where('stalls_id',$stallId)->column('id');
				$where[]=['order_material_item_id','in',$omiIds];
			}
			$orderMaterialItemService=new OrderMaterialItemService();
    		$where[]=['is_delivery','=',2];
    		$order = 'id desc';
    		$order = 'update_time desc';
    		$data['data'] = db('material_return')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum');
				$omiInfo=$orderMaterialItemService->getInfoById($v['order_material_item_id']);
				$data['data'][$k]['stall_name']=$omiInfo?arrayGet($stallsKV, $omiInfo['stalls_id'],''):'';
				$data['data'][$k]['type_num'] = $v['type']==1?'整条退':'退料米长';
				$data['data'][$k]['delivery_admin_name']=arrayGet($systemUserKV, $v['delivery_admin_id'],'');
    		}

    		$data['count'] = db('material_return')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
    	$assign = [
			'today'=>time(),
			'stallsKV' => ['0' => '请选择'] + $stallsKV
    	];
    	return $this->assign($assign)->fetch();
    }
	/**
     * 打印模板
     *
     * @author 飞燕
     * @date 2021年4月15日
     *
     * @return Json
     */
	public function analysis(){
		$ids         = $this->request->param('id', []);
		$materialService=new materialService();
		$orderMaterialItemService=new OrderMaterialItemService();
		$stallsKV= getStallsKV();
		$where[]=['id','in',$ids];
		$data = db('material_return')->where($where)->select();
		foreach ($data as $k => $v) {
			$data[$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum');
			$omiInfo=$orderMaterialItemService->getInfoById($v['order_material_item_id']);
			$data[$k]['stall_name']=$omiInfo?arrayGet($stallsKV, $omiInfo['stalls_id'],''):'';
			$data[$k]['stall_id']=$omiInfo['stalls_id'];
			$data[$k]['type_num'] = $v['type']==1?'整条退':$v['return_length'];
		}
		$dataNew=[];
		foreach ($data as $key => $value) {
			$dataNew[$value['stall_name']][]=$value;
		}
		return $this->Json(1,'操作成功',$dataNew);
	}
	/**
     * 出库打印
     *
     * @author KING
     * @date 2020年7月17日
     *
     */
    public function print() {
    	$ids         = $this->request->param('id', []);
		$materialService=new materialService();
		$orderMaterialItemService=new OrderMaterialItemService();
		$stallsKV= getStallsKV();
		$where[]=['id','in',$ids];
		$data = db('material_return')->where($where)->select();
		foreach ($data as $k => $v) {
			$data[$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum');
			$omiInfo=$orderMaterialItemService->getInfoById($v['order_material_item_id']);
			$data[$k]['stall_name']=$omiInfo?arrayGet($stallsKV, $omiInfo['stalls_id'],''):'';
			$data[$k]['stall_id']=$omiInfo['stalls_id'];
			$data[$k]['type_num'] = $v['type']==1?'整条退':$v['return_length'];
		}
		$dataNew=[];
		foreach ($data as $key => $value) {
			$dataNew[$value['stall_name']][]=$value;
		}
		$assign['data']=$dataNew;
		$assign['systemUserKV']= getSystemUserKV(null);

    	$this->view->engine->layout('system@layout_empty');
    	return $this->assign($assign)->fetch();
    }

	/**
     * 出库
     *
     * @author 飞燕
     * @date 2021年01月15日
     *
     */
    public function delivery() {
    	$ids         = $this->request->param('id/s');
		$where[]=['id','in',$ids];
		$upData = [
			'is_delivery' => 2,
			'update_time' => time(),
			'delivery_admin_id'=>ADMIN_ID,
			'delivery_time'=>time()
		];
		$res=db('material_return')->where($where)->update($upData);
		if($res) {
			$materialReturnService = new MaterialReturnService();
			foreach ($ids as $id) {
				$mrInfo = $materialReturnService->getInfoById($id, 'order_id,client_ordernum,material_id,cloth_num');
				if ($mrInfo) {
					$materialName = getMaterialName($mrInfo['material_id']);
					$this->addOrderLog($mrInfo['order_id'], $mrInfo['client_ordernum'], "物料[{$materialName}]布号{$mrInfo['cloth_num']}退换料进度 出库");
				}
			}
			return $this->Json(1);
		} else{
    		return $this->Json(0);
		}
    }

    /**
     * 修改退换料长度
     *
     * @author King
     * @date 2021年9月2日
     *
     */
	public function returnLengthEdit(){
		$id       = $this->request->param('id/d', 0);
    	$returnLength   = $this->request->param('return_length/f', 0);
		$materialReturnService=new MaterialReturnService();
		$mrInfo=$materialReturnService->getInfoById($id);
		if(!$mrInfo)			return $this->error("数据异常");
    	$upData = [
			'return_length'=>$returnLength,
    		'update_time' => time(),
    	];
    	$ret = db('material_return')->where('id', $id)->update($upData);
    	$this->addOrderLog($mrInfo['order_id'], '', "修改物料[".getMaterialName($mrInfo['material_id'])."]退换料长度为{$returnLength}");
    	if ($ret) {
    		return $this->Json(1, '修改退换料长度成功');
    	} else return $this->Json(0);
	}
}